package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_house/api/request"
	"new_house/internal/dao"
	"new_house/internal/model"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 1) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "该用户无权限创建购房订单",
			"data":    nil,
		})
		return
	}
	result := dao.Create(&model.Order{
		UserId:   c.GetUint("userId"),
		HouseId:  req.HouseId,
		OrderUrl: req.OrderUrl,
	})
	if !result {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "创建房源订单失败",
			"data":    false,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "创建房源订单成功",
		"data":    true,
	})
	dao.Update(&model.House{
		Id:     req.HouseId,
		Status: 4,
	})
}

func UploadOrderUrl(c *gin.Context) {
	var req request.UploadOrderUrlReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 1) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "该用户无权限上传首付款凭证接口",
			"data":    nil,
		})
		return
	}
	dao.Update(&model.Order{
		Id:       req.Id,
		OrderUrl: req.OrderUrl,
		Status:   req.Status,
	})
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "订单状态变更成功",
		"data":    true,
	})

}

func GetOrderPageList(c *gin.Context) {
	var req request.GetOrderPageListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 3) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "只有管理员有权限查看订单",
			"data":    nil,
		})
		return
	}
	pageDto := dao.PageDto{
		Page:     req.Page,
		PageSize: req.PageSize,
	}
	var orderList []model.Order
	paginate, _ := dao.Paginate(&model.Order{
		Id: req.Id,
	}, pageDto, &orderList)
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "订单分页展示成功",
		"data":    paginate,
	})
}

func UpdateOrderStatus(c *gin.Context) {
	var req request.UpdateOrderStatusReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.UType == 3) {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "只有管理员有权限修改订单状态",
			"data":    nil,
		})
		return
	}
	dao.Update(&model.Order{
		Id:     req.Id,
		Status: req.Status,
	})
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "订单状态变更成功",
		"data":    true,
	})
}
